<?php

namespace app\home\controller;

use think\Controller;
// use app\common\controller\Home AS HomeController;
use app\common\controller\Home;
use think\Cookie;

class User extends Home
{

    // 构造函数
    public function __construct()
    {
        parent::__construct();

        // 引用用户模型
        $this->UserModel = model('User.User');
        $this->RegionModel = model('Region');
        $this->PostModel = model('Post.Post');
        $this->CollectModel = model('User.Collect');
    }

    //用户首主页
    public function index()
    {
        //接收用户id
        $id = $this->request->param('id', 0);

        // 根据id去查询数据表是否该用户
        $User = $this->UserModel->find($id);

        if ($User) {
            // 如果有数据或者$User等于true 说明查看别人的个人中心
            // 如果有这个用户的时候，就显示user模板
            $this->assign([
                'User' => $User
            ]);
            return $this->fetch('user');
        } else {
            // 显示index模板 说明查看自己个人中心
            return $this->fetch();
        }
    }

    //用户中心
    public function home()
    {
        //获取点击的是发帖,还是收藏
        $postStatus = $this->request->param('postStatus', 0);

        //判断点击的是发帖,还是收藏


        //查询该用户的帖子 
        $postList = $this->PostModel->where(['userid' => $this->LoginUser['id']])->select();

        //查询该用户的收藏
        $collectList = $this->CollectModel->where(['userid' => $this->LoginUser['id']])->select();

        $this->assign([
            'postList' => $postList, //帖子数据
            'collectList' => $collectList, //收藏数据
            'postStatus' => $postStatus
        ]);

        return $this->fetch();
    }

    //基本设置
    public function profile()
    {
        if ($this->request->isPost()) {
            //接收隐藏域
            $action = $this->request->param('action', '');

            //接收所有数据
            $params = $this->request->param();

            //判断是否是修改我的资料
            if ($action == 'profile') {

                //封装数据
                $data = [
                    'id' => $this->LoginUser['id'],
                    'email' => $params['email'],
                    'nickname' => $params['nickname'],
                    'sex' => $params['sex'],
                    'province' => $params['province'],
                    'city' => $params['city'],
                    'district' => $params['district'],
                    'content' => $params['content'],
                ];

                //说明邮箱已经修改
                if ($params['email'] != $this->LoginUser['email']) {
                    $data['auth'] = 0;
                }

                $result = $this->UserModel->validate('common/user/User.profile')->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    $this->error($this->UserModel->getError());
                    exit;
                } else {
                    // 封装一个cookie数据
                    $data = [
                        'id' => $this->LoginUser['id'],
                        'email' => $params['email'],
                        'nickname' => $params['nickname'],
                        'vip' => $this->LoginUser['vip'],
                        'auth' => $this->LoginUser['auth'],
                        'point' => $this->LoginUser['point'],
                        'avatar' => is_file($this->LoginUser['avatar']) ? $this->LoginUser['avatar'] : '/static/home/res/images/avatar.jpg',
                        'cover' => is_file($this->LoginUser['cover']) ? $this->LoginUser['cover'] : '/static/home/res/images/back.jpg'
                    ];

                    //说明邮箱已经修改
                    if ($params['email'] != $this->LoginUser['email']) {
                        $data['auth'] = 0;
                    }

                    // 设置cookie
                    Cookie::set('LoginUser', $data);
                    $this->success('个人资料更新成功', url('home/user/profile'));
                    exit;
                }
            }

            //上传封面图
            if ($action == 'cover') {
                $cover = upload('cover');

                if ($cover == FALSE) {
                    $this->error('上传失败');
                    exit;
                }

                //封装数据
                $data = [
                    'id' => $this->LoginUser['id'],
                    'cover' => $cover,
                ];

                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    //上传失败
                    //删除上传上来的图片
                    @is_file($data['cover']) && @unlink($data['cover']);
                    $this->error('封面图更新失败');
                    exit;
                } else {
                    //上传成功
                    //删除原来的旧图片
                    $cover = ltrim($this->LoginUser['cover'], "/");
                    @is_file($cover) && @unlink($cover);

                    $cover = ltrim($data['cover'], "/");
                    //设置一个保存cookie的信息
                    $cookie = [
                        'id' => $this->LoginUser['id'],
                        'nickname' => $this->LoginUser['nickname'],
                        'vip' => $this->LoginUser['vip'],
                        'auth' => $this->LoginUser['auth'],
                        'avatar' => is_file($this->LoginUser['avatar']) ? $this->LoginUser['avatar'] : '/static/home/res/images/avatar.jpg',
                        'cover' => is_file($cover) ?  $data['cover'] : '/static/home/res/images/back.jpg'
                    ];

                    //将用户信息设置到cookie里面
                    Cookie::set('LoginUser', $cookie);

                    $this->success('封面图更新成功');
                    exit;
                }
            }
        }

        //查看cookie
        // halt(Cookie::get('LoginUser'));

        //查询省
        $province = $this->RegionModel->where(['grade' => 1])->select();

        //查询市
        if (empty($this->LoginUser['province'])) {
            $city = [];
        } else {
            $city = $this->RegionModel->where(['parentid' => $this->LoginUser['province']])->select();
        }

        //查询区
        if (empty($this->LoginUser['city'])) {
            $district = [];
        } else {
            $district = $this->RegionModel->where(['parentid' => $this->LoginUser['city']])->select();
        }

        //赋值
        $this->assign([
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);

        return $this->fetch();
    }

    //查询地区(接口)
    public function area()
    {
        if ($this->request->isAjax()) {
            $code = $this->request->param('code', 0);

            $code = trim($code);

            $result = $this->RegionModel->where(['parentid' => $code])->select();

            if ($result === FALSE) {
                $this->warning('查询失败');
                exit;
            } else {
                $this->finish('查询成功', $result);
            }
        }
    }

    //我的消息
    public function message()
    {
        return $this->fetch();
    }

    //发送验证邮件
    public function email()
    {
        //判断是否是Ajax请求
        if ($this->request->isAjax()) {

            //引用邮箱类(第三方类)
            include_once(APP_PATH . 'phpmail/class.phpmailer.php');

            //实例化
            $mail = new \PHPMailer(true);

            //开启SMTP
            $mail->IsSMTP();

            //允许发送HTMl内容
            $mail->IsHTML(true);

            //SMTP服务器
            $mail->Host = "smtp.qq.com";

            //开启smtp认证
            $mail->SMTPAuth = true;

            //设置smtp的邮箱用户
            $mail->Username = '3467703528@qq.com'; //STMP用户名

            //在qq邮箱生成的授权码
            $mail->Password = "ziupgeqfhtoldade";

            //端口
            $mail->Port = 25;

            //发件人的邮箱
            $mail->From = "3467703528@qq.com";

            //发件人名字
            $mail->FromName = "ask社区";

            //收件人的邮箱
            $mail->AddAddress(
                $this->LoginUser['email'],
                $this->LoginUser['nickname']
            );

            //邮件的主题
            $mail->Subject = "ask社区认证";

            //接受请求过来的参数
            $email = $this->request->param('email', '');

            $email = md5($email);

            //封装的内容
            $msg = "<a href='http://www.asks.com/home/index/email?email=$email'>免费激活邮箱</a>";

            //邮件的内容
            $mail->Body = $msg;

            //发送
            $result =  $mail->send();

            if ($result == FALSE) {
                $this->warning('发送邮件失败!');
                exit;
            } else {
                $this->success('发送邮件成功');
                exit;
            }
        }
    }
}
